<?php
/**
 * MYSQL数据操作方法封装类
 * [MySQLi]
 */

class wmysql
{
	/**
	 * 内部数据连接对象
	 * @var mysqli
	 */
	private $conn;

	/**
	 * 内部实例对象
	 * @var object MySql
	 */
	private static $instance = null;

	/**
	 * 构造函数
	 * @param string $host 数据库主机
	 * @param string $user 用户名
	 * @param string $pw 密码
	 * @param string $name 数据库名
	 * @param bool $long 是否开启长连接
	 */
	public function __construct($host, $user, $pw, $name, $long = false)
	{
		if (!class_exists('mysqli')) {
			throw new Exception('服务器不支持MySqli类');
		}
		$coninfo = strpos($host, ':');
		if ($coninfo === false) {
			if ($long) {
				$host = 'p:' . $host;
			}
			@$this->conn = new mysqli($host, $user, $pw, $name);
		} else {
			if ($long) {
				@$this->conn = new mysqli('p:' . substr($host, 0, $coninfo), $user, $pw, $name, substr($host, $coninfo + 1));
			} else {
				@$this->conn = new mysqli(substr($host, 0, $coninfo), $user, $pw, $name, substr($host, $coninfo + 1));
			}
		}

		if ($this->conn->connect_error) {
			switch ($this->conn->connect_errno) {
				case 1044:
				case 1045:
					throw new Exception("连接数据库失败，数据库用户名或密码错误", 10000);
					break;

				case 1049:
					throw new Exception("连接数据库失败，未找到您填写的数据库", 10000);
					break;

				case 2003:
					throw new Exception("连接数据库失败，数据库端口错误", 10000);
					break;

				case 2005:
					throw new Exception("连接数据库失败，数据库地址错误或者数据库服务器不可用", 10000);
					break;

				case 2006:
					throw new Exception("连接数据库失败，数据库服务器不可用", 10000);
					break;

				default:
					throw new Exception("连接数据库失败，请检查数据库信息。错误编号：" . $this->conn->connect_errno, 10000);
					break;
			}
		}

		$this->conn->set_charset('utf8');
		self::$instance = $this->conn;
		return self::$instance;
	}

	/**
	 * 关闭数据库连接
	 */
	public function close()
	{
		return $this->conn->close();
	}

	/**
	 * 发送查询语句
	 *
	 */
	public function query($sql, $noerror = false)
	{
		$this->result = $this->conn->query($sql);
		$this->queryCount++;
		if (!$this->result) {
			if ($noerror == true) {
				return false;
			} else {
				throw new Exception("MySQL 语句执行错误：<br/><b>语句：</b>$sql<br/><b>错误：</b>" . $this->geterror(), 10000);
			}
		} else {
			return $this->result;
		}
	}

	/**
	 * 获取stmt
	 * @param string $sql
	 * @return mysqli_stmt
	 */
	public function get_stmt($sql)
	{
		return $this->conn->prepare($sql);
	}
}
